﻿// Copyright (c) 2012 - 2021 Jared Zheng <jaredz at outlook dot com>
// Buddha Framework is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
//
// Create : 2012-12-01 version 0.1 Jared Zheng <jaredz at outlook dot com>
// Update : 2021-03-19 version 4.0.0 Jared Zheng <jaredz at outlook dot com>

#ifndef __COMMON_HANDLER_H__
#define __COMMON_HANDLER_H__

#pragma once

#include "CommonServer.h"

///////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 服务通用处理
class CCommonHandler : public CEventHandler
{
public:
    enum STATUS_UPDATE
    {
        STATUS_UPDATE_LOOP = 4,
        STATUS_UPDATE_MAX  = 5,
    };
public:
    CCommonHandler(void);
    virtual ~CCommonHandler(void);

    bool Init(UInt uRank);
    void Exit(void);
    bool Start(void);
    void Stop(bool bUnlink = true);
    // CEventHandler
    virtual UInt OnHandle(uintptr_t utEvent, uintptr_t utData, ULLong ullParam) OVERRIDE;
    virtual UInt OnHandle(uintptr_t utEvent, CEventBase& EventRef, ULLong ullParam) OVERRIDE;
    virtual UInt OnHandle(uintptr_t utEvent, CStream& Stream, ULLong ullParam) OVERRIDE;
    virtual UInt OnHandle(uintptr_t utEvent, UInt uCount) OVERRIDE;
protected:
    void UpdateStatus(void);

    void OnLink(PAIR_INFO* pInfo, UInt uRank);
    void OnLinkAck(Socket_t sSocket, UInt uRank);

    void OnUpdate(PAIR_INFO* pInfo, UInt uRank);
    void OnUpdateAck(PSERVER_DATA pData, UInt uRank);

    void OnSync(PSERVER_STATUS pStatus, UInt uRank);
    void OnSyncAck(PSERVER_CLUSTER pCluster, UInt uRank);
    void OnSyncAckStatus(const SERVER_CONFIG& sc, PAIR_INFO* pInfo, UInt uRank);
    
    void OnUnlink(PAIR_INFO* pInfo, UInt uRank);
    void OnUnlinkAck(Socket_t sSocket, UInt uRank);

    void OnTcpListen(Socket_t sSocket, UInt uRank);
    void OnTcpListenClose(Socket_t sSocket, UInt uRank);

    void OnTcpConnect(Socket_t sSocket, UInt uRank);
    void OnTcpConnectClose(Socket_t sSocket, UInt uRank);
protected:
    Int         m_nLoop;
    Int         m_nUpdate;
    UInt        m_uRank;
    CFramePtr   m_FramePtr;
};

INLINE CCommonHandler::CCommonHandler(void)
: m_nLoop(0)
, m_nUpdate(0)
, m_uRank(COMMONT_NONE)
{
    AddRef(); // 防止m_MgrHandler->Release时错误释放handler
}

INLINE CCommonHandler::~CCommonHandler(void)
{
    Exit();
}

#endif // __COMMON_HANDLER_H__
